import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Modal, Button, Input, DatePicker, Select, message } from 'antd';
import { connect } from 'react-redux';
import { get } from 'lodash';
import moment from 'moment';
import validatorCreator from '@util/validator-creator';
import { PHONE_RE, EMAIL_RE, USER_NAME_RE, REAL_NAME_RE } from '@util/constants';
import { addUser, updateUser } from '@api/user';
import rsa from '@util/rsa';
import './index.less';

const { Item: FormItem } = Form;
const { Option: SelectOption } = Select;

class AddEditModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(props) {
    const {
      form: { resetFields, setFieldsValue },
      values
    } = props;
    if (this.props.visible && !props.visible) {
      resetFields();
    } else if (values && !this.props.visible && props.visible) {
      if (values.expired) {
        values.expired = moment(values.expired, 'YYYY-MM-DD HH:mm:ss');
      }
      setFieldsValue(values);
    }
  }

  onModalOk = () => {
    const {
      form: { validateFields },
      values,
      onSuccess
    } = this.props;
    const uid = get(values, '_id');
    const todo = uid ? updateUser : addUser;
    const desc = uid ? '编辑' : '添加';
    validateFields((errors, values) => {
      if (errors) {
        return;
      }
      if (values.expired) {
        values.expired = moment(values.expired).format('YYYY-MM-DD 00:00:00');
      } else {
        values.expired = '';
      }
      if (uid) {
        values['user_id'] = uid;
        delete values.username;
      } else {
        values['publicKey'] = rsa.getKeys('local').public;
      }
      this.setState({ loading: true });

      todo(values)
        .then(res => {
          const password = get(res, 'data.data.password');
          const decryptedPassword = password
            ? rsa.decrypt(password, rsa.getKeys('local').private)
            : '';
          if (typeof onSuccess === 'function') {
            onSuccess(decryptedPassword, uid);
          }
        })
        .catch(error => {
          if (error && error.type === 'parsed') {
            return message.error(`${desc}用户失败:${error.message}`);
          }
          message.error(`${desc}用户失败`);
        })
        .finally(() => {
          this.setState({ loading: false });
        });
    });
  };

  disabledDate = date => {
    return date.valueOf() <= Date.now();
  };

  render() {
    const {
      form: { getFieldDecorator },
      onCancel,
      visible,
      title,
      roles,
      values
    } = this.props;

    const uid = get(values, '_id');

    const { loading } = this.state;

    const inputFormItems = [
      {
        key: 'username',
        label: '用户名',
        required: true,
        disabled: Boolean(uid),
        reg: USER_NAME_RE,
        min: 3,
        max: 32
      },
      {
        key: 'nickname',
        label: '姓名',
        required: true,
        reg: REAL_NAME_RE,
        min: 2,
        max: 32
      },
      {
        key: 'email',
        label: '邮箱',
        reg: EMAIL_RE
      },
      {
        key: 'phone',
        label: '手机号',
        reg: PHONE_RE,
        required: true
      }
    ];

    const footer = [
      <Button key="0" onClick={onCancel}>
        取消
      </Button>,
      <Button key="1" type="primary" onClick={this.onModalOk} loading={loading}>
        确定
      </Button>
    ];

    const formItemLayout = {
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 18
      }
    };

    const filteredRoles = roles.filter(i => i && !i.is_admin);
    return (
      <Modal
        maskClosable={false}
        className="user-manage-add-edit-modal"
        visible={visible}
        title={title}
        onCancel={onCancel}
        footer={footer}
      >
        <Form>
          {inputFormItems.map(item => {
            const { key, label, reg, min, max, required = false, disabled = false } = item;
            const rules = [
              {
                required: required,
                message: `${label}不能为空`
              },
              {
                validator: validatorCreator(label, {
                  reg,
                  min,
                  max
                })
              }
            ];
            return (
              <FormItem key={key} {...formItemLayout} label={label} colon={false}>
                {getFieldDecorator(key, {
                  rules: rules
                })(<Input placeholder={`请输入${label}`} disabled={disabled} />)}
              </FormItem>
            );
          })}
          <FormItem {...formItemLayout} label={'失效日期'} colon={false}>
            {getFieldDecorator('expired')(<DatePicker disabledDate={this.disabledDate} />)}
          </FormItem>
          <FormItem {...formItemLayout} label={'账号类型'} colon={false}>
            {getFieldDecorator('role_id', {
              rules: [{ required: true, message: '账号类型不能为空' }]
            })(
              <Select>
                {filteredRoles.map(role => {
                  const { _id, name } = role;
                  const option = (
                    <SelectOption key={_id} value={_id}>
                      {name}
                    </SelectOption>
                  );
                  return option;
                })}
              </Select>
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

AddEditModal.propTypes = {
  form: PropTypes.object,
  onSuccess: PropTypes.func,
  onCancel: PropTypes.func,
  visible: PropTypes.bool,
  values: PropTypes.object,
  title: PropTypes.string,
  roles: PropTypes.array
};

const mapStateToProps = state => {
  return {
    roles: get(state, 'role.roles', [])
  };
};

export default connect(
  mapStateToProps,
  null
)(Form.create()(AddEditModal));
